﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.IO;
using System.Text;

namespace BookDemo.S09.S914
{
    class S914 : IBookDemo
    {
        public void Main(string[] args)
        {
            File.AppendAllLines("log.csv", new string[] { $"EventName, Payload, ActivityId, RelatedActivityId" });
            _ = new LoggingEventListener();
            var logger = new ServiceCollection()
                .AddLogging(builder => builder.AddEventSourceLogger())
                .BuildServiceProvider()
                .GetRequiredService<ILogger<Program>>();

            using (logger.BeginScope(new Dictionary<string, object> { ["Operation"] = "Foo" }))
            {
                logger.LogInformation("This is a test log written in scope 'Foo'");
                using (logger.BeginScope(new Dictionary<string, object> { ["Operation"] = "Bar" }))
                {
                    logger.LogInformation("This is a test log written in scope 'Bar'");
                }
                using (logger.BeginScope(new Dictionary<string, object> { ["Operation"] = "Baz" }))
                {
                    logger.LogInformation("This is a test log written in scope 'Baz'");
                }
            }
        }
    }
    public class LoggingEventListener : EventListener
    {
        protected override void OnEventSourceCreated(EventSource eventSource)
        {
            if (eventSource.Name == "System.Threading.Tasks.TplEventSource")
            {
                EnableEvents(eventSource, EventLevel.Informational, (EventKeywords)0x80);
            }

            if (eventSource.Name == "Microsoft-Extensions-Logging")
            {
                EnableEvents(eventSource, EventLevel.LogAlways, (EventKeywords)8);
            }
        }

        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            int index;
            var payload = (index = eventData.PayloadNames.IndexOf("ArgumentsJson")) == -1
                ? null
                : eventData.Payload[index];
            var relatedActivityId = eventData.RelatedActivityId == default(Guid)
                ? ""
                : eventData.RelatedActivityId.ToString();

            File.AppendAllLines("log.csv", new string[] { $"{eventData.EventName}, {payload}, {eventData.ActivityId}, {relatedActivityId}" });
        }
    }
}
